package com.example.forum.services.imp;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.ArticleMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoardService;
import com.example.forum.services.IUserService;
import com.example.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

@Service
@Slf4j
public class ArticleServiceImpl implements IArticleService {

    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private IUserService userService;
    @Resource
    private IBoardService boardService;
    @Resource
    private ThreadPoolTaskExecutor taskExecutor;

    @Override
    public void create(Article article) throws ExecutionException, InterruptedException {
        //非空校验
        if (article == null || article.getBoardId() == null || article.getUserId() == null ||
                StringUtil.isEmpty(article.getTitle()) ||
                StringUtil.isEmpty(article.getContent())) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //设置默认值
        article.setVisitCount(0);  //访问数量
        article.setReplyCount(0);  //回复数量
        article.setLikeCount(0);   //点赞数
        article.setDeleteState((byte) 0);
        article.setState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);

        //写入数据库
        int articleRow = articleMapper.insertSelective(article);
        if (articleRow <= 0) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        //多线程处理 同时添加用户文章数和板块下文章数

        //更新用户发帖数
        FutureTask<?> userCount = new FutureTask(() -> {
            //将用户文章数量+1
            //获取用户信息
            User user = userService.SelectById(article.getUserId());
            if (user == null) {
                log.warn(ResultCode.FAILED_CREATE.toString() + "发帖失败 user id = " + user.getId());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
            }
            userService.addOneArticleCountById(user.getId());
            log.info("处理线程名" + Thread.currentThread().getName());
            return null;
        });
        taskExecutor.submit(userCount);


        FutureTask<?> boardCount = new FutureTask(() -> {
            //对应板块下数量+1  获取板块信息
            Board board = boardService.selectById(article.getBoardId());
            //是否在数据库中有对应的板块
            if (board == null) {
                log.warn(ResultCode.FAILED_CREATE.toString() + "发帖失败 board id = " + article.getBoardId());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
            }
            boardService.addOneArticleCountById(board.getId());
            log.info("处理线程名" + Thread.currentThread().getName());
            return null;
        });
        taskExecutor.submit(boardCount);

        //等待线程执行完成
        userCount.get();
        boardCount.get();

        //单线程处理
        /*//获取用户信息
        User user = userService.SelectById(article.getUserId());
        //没有找到指定用户信息
        if (user == null) {
            log.warn(ResultCode.FAILED_CREATE.toString() + "发帖失败 user id = " + user.getId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //更新用户发帖数
        userService.addOneArticleCountById(user.getId());

        //获取板块信息
        Board board = boardService.selectById(article.getBoardId());
        //是否在数据库中有对应的板块
        if (board == null) {
            log.warn(ResultCode.FAILED_CREATE.toString() + "发帖失败 board id = " + article.getBoardId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //更新板块中帖子数量
        boardService.addOneArticleCountById(board.getId());*/
        //打印日志
        log.info(ResultCode.SUCCESS.toString() + "user id = " + article.getUserId()
                + "board id = " + article.getBoardId() + "article id = " + article.getId() + "发帖成功");
        //throw new ApplicationException(AppResult.failed("测试事务回滚"));
    }

    @Override
    public List<Article> selectAll() {
        //调用DAO
        List<Article> articles = articleMapper.selectAll();
        log.info("业务需要查询数据库");
        return articles;
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        //校验参数
        if(userId == null || userId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验用户是否存在
        User user = userService.SelectById(userId);
        if(user == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString()+"user id = " + userId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //调用dao
        List<Article> articles = articleMapper.selectByUserId(userId);
        return articles;
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        //非空校验
        if (boardId == null || boardId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询boardId是否存在
        Board board = boardService.selectById(boardId);
        if (board == null) {
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString() + ", boardId = " + boardId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        //调用dao查询指定板块下的所有列表
        List<Article> articles = articleMapper.selectAllByBoardId(boardId);
        return articles;
    }

    @Override
    public Article selectDetailById(Long id) {
        //非空校验
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询结果
        Article article = articleMapper.selectDetailById(id);
        if (article == null) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //更新帖子访问次数
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount() + 1);
        // 将访问次数保存到数据库
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //为返回对象进行更新访问次数
        article.setVisitCount(article.getVisitCount() + 1);
        //返回帖子详情
        return article;
    }

    @Override
    public Article selectById(Long id) {
        //非空校验
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用dao
        Article article = articleMapper.selectByPrimaryKey(id);
        //返回结果
        return article;
    }

    @Override
    public void modify(Long id, String title, String content) {
        //非空校验
        if (id == null || id <= 0 || StringUtil.isEmpty(title) ||
                StringUtil.isEmpty(content)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //构建要更新的帖子对象
        Article updateArticle = new Article();
        updateArticle.setId(id);  //id
        updateArticle.setTitle(title);  //标题
        updateArticle.setContent(content);   //正文
        updateArticle.setUpdateTime(new Date());  //更新时间
        //调用dao执行
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void thumbsUpById(Long id) {
        //非空校验
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取帖子详情
        Article article = articleMapper.selectByPrimaryKey(id);
        //帖子不存在
        if (article == null  || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //帖子状态异常
        if (article.getState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //构造要更新的对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount()+1);
        updateArticle.setUpdateTime(new Date());
        //更新
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void deleteById(Long id) throws ExecutionException, InterruptedException {
        //非空校验
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //根据id查询帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article == null || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString()+", article id = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //构造一个更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);
        //调用dao
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

        //更新板块中帖子数量和用户帖子数量  多线程操作
        FutureTask<?> boardCount = new FutureTask(()->{
            boardService.subOneArticleCountByID(article.getBoardId());
            log.info("处理线程名" + Thread.currentThread().getName());
            return null;
        });
        taskExecutor.submit(boardCount);
        FutureTask<?> userCount = new FutureTask(()->{
            userService.subOneArticleCountById(article.getUserId());
            log.info("处理线程名" + Thread.currentThread().getName());
            return null;
        });
        taskExecutor.submit(userCount);
        boardCount.get();
        userCount.get();

        //更新板块中帖子数量和用户帖子数量 单线程操作
        /*boardService.subOneArticleCountByID(article.getBoardId());
        userService.subOneArticleCountById(article.getUserId());*/
        log.info("删除帖子成功 article id = " + article.getId() + " user id = " + article.getUserId());
    }

    @Override
    public void addOneReplyCountById(Long id) {
        //非空校验
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        //校验帖子信息
        if(article == null || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //帖子已经封贴
        if(article.getState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        //回复数+1
        updateArticle.setReplyCount(article.getReplyCount()+1);
        updateArticle.setUpdateTime(new Date());
        //调用dao
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public List<Article> selectSearch(String artName) {
        if(StringUtil.isEmpty(artName) == null) {
            log.warn(ResultCode.FAILED.toString()+"搜索词为空");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        List<Article> articles = articleMapper.selectSearch(artName);
        if(articles == null) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        return articles;
    }

    @Override
    public List<Article> selectBoarSearch(String artName, Long boardId) {
        if(StringUtil.isEmpty(artName) == null) {
            log.warn(ResultCode.FAILED.toString()+"搜索词为空");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        if(boardId == null || boardId < 1) {
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        List<Article> articles = articleMapper.selectBoarSearch(artName,boardId);
        if(articles == null) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        return articles;
    }

}
